import 'package:appsflyer_sdk/appsflyer_sdk.dart';

class AppsFlyerEventManager {
  static AppsflyerSdk? _appsflyerSdk;

  static void initialize(AppsflyerSdk sdk) {
    _appsflyerSdk = sdk;
  }

  // 应用打开事件
  static Future<bool?> logAppOpened() async {
    return await _logEvent('af_app_opened', {});
  }

  // 用户注册事件
  static Future<bool?> logRegistration({String? method, String? userId}) async {
    return await _logEvent('登记', {});
  }

  static Future<bool?> logAddCart() async {
    return await _logEvent('添加购物车', {});
  }

  static Future<bool?> logFristTouup() async {
    return await _logEvent('firstRecharge', {});
  }

  // 添加购物车事件
  static Future<bool?> logAddToCart({
    required String productId,
    required String productName,
    required double price,
    required String currency,
    int quantity = 1,
  }) async {
    return await _logEvent('af_add_to_cart', {
      'af_content_id': productId,
      'af_content_type': 'product',
      'af_currency': currency,
      'af_price': price.toString(),
      'af_quantity': quantity.toString(),
      'product_name': productName,
    });
  }

  // 首次充值事件
  static Future<bool?> logFirstRecharge({
    required double amount,
    required String currency,
    String? paymentMethod,
    String? orderId,
  }) async {
    Map<String, dynamic> eventValues = {
      'af_revenue': amount.toString(),
      'af_currency': currency,
      'af_content_type': 'first_recharge',
      'event_time': DateTime.now().millisecondsSinceEpoch.toString(),
    };

    if (paymentMethod != null) {
      eventValues['af_payment_method'] = paymentMethod;
    }

    if (orderId != null) {
      eventValues['af_order_id'] = orderId;
    }

    return await _logEvent('firstRecharge', eventValues);
  }

  // 购买完成事件
  static Future<bool?> logPurchase({
    required String productId,
    required double revenue,
    required String currency,
    String? orderId,
    int quantity = 1,
  }) async {
    Map<String, dynamic> eventValues = {
      'af_content_id': productId,
      'af_revenue': revenue.toString(),
      'af_currency': currency,
      'af_quantity': quantity.toString(),
      'af_content_type': 'product',
    };

    if (orderId != null) {
      eventValues['af_order_id'] = orderId;
    }

    return await _logEvent('af_purchase', eventValues);
  }

  // 自定义事件
  static Future<bool?> logCustomEvent(
    String eventName,
    Map<String, dynamic> eventValues,
  ) async {
    return await _logEvent(eventName, eventValues);
  }

  // 私有方法：统一的事件上报
  static Future<bool?> _logEvent(
    String eventName,
    Map<String, dynamic> eventValues,
  ) async {
    print('🔍 [DEBUG] _logEvent called with: $eventName');
    print('🔍 [DEBUG] SDK状态: ${_appsflyerSdk != null ? '已初始化' : '未初始化'}');

    if (_appsflyerSdk == null) {
      print('❌ AppsFlyer SDK not initialized');
      return false;
    }

    try {
      print('📊 Logging event: $eventName');
      print('📊 Event values: $eventValues');

      final result = await _appsflyerSdk!.logEvent(eventName, eventValues);
      print('✅ Event logged successfully: $eventName, result: $result');
      print('✅ Result type: ${result.runtimeType}');
      return result;
    } catch (e) {
      print('❌ Failed to log event $eventName: $e');
      print('❌ Exception type: ${e.runtimeType}');
      print('❌ Stack trace: ${StackTrace.current}');
      return false;
    }
  }
}
